/* eslint-disable no-irregular-whitespace */
import axios from 'axios' // 引用axios
import { getCookie } from './util'
import NotificationInfo from '@/Views/components/kendo-vue-component/notify/index'
const ah = require('ajax-hook')
ah.proxy({
  onRequest: function(config, handler) {
    debugger
    const url = config.url
    const body = config.body
    if (body instanceof FormData) {
      handler.next(config)
    } else if (url.indexOf('/service/imageBrowser') > -1 || url.indexOf('/service/imagePreview') > -1) {
      handler.next(config)
    } else {
      const parameterMap = JSON.parse(body) === null ? {} : JSON.parse(body)
      parameterMap.token = getCookie('token')
      config.body = JSON.stringify(parameterMap)
      handler.next(config)
    }
  },
  onResponse: (response, handler) => {
    if (response.status !== 200) {
      NotificationInfo.install({
        title: '错误提示：' + response.status,
        message: response.statusText
      }, 'error')
    } else {
      if (typeof response.response === 'string') {
        const responseData = JSON.parse(response.response)
        if (responseData.code !== 200) {
          NotificationInfo.install({
            title: '错误提示：' + responseData.code,
            message: responseData.message
          }, 'error')
        }
      }
    }
    handler.next(response)
  }
})
// ah.hook({
//   open: function(arg, xhr) {
//     debugger
//     const argSplit = arg[1].split('?')
//     let parameterMap = {}
//     let parameterKey = {}
//     if (argSplit.length > 1) {
//       parameterMap = JSON.parse(argSplit[1].split('=')[1])
//       parameterMap.token = getCookie('token')
//       parameterKey = argSplit[1].split('=')[0]
//       arg[1] = argSplit[0] + '?' + `${parameterKey}` + `${JSON.stringify(parameterMap)}`
//     } else {
//       if (argSplit[0].indexOf('/service') >= 0) {
//         const token = getCookie('token')
//         if (!isBlank(token)) {
//           arg[1] += '?token=' + `${getCookie('token')}`
//         }
//       }
//     }
//   },
//   onload(xhr) {
//     if (xhr !== undefined && xhr.status !== 200) {
//       NotificationInfo.install({
//         title: '错误提示：' + xhr.status,
//         message: xhr.statusText
//       }, 'error')
//     } else {
//       if (typeof xhr.response === 'string') {
//         const responseData = JSON.parse(xhr.response)
//         if (responseData.code !== 200) {
//           NotificationInfo.install({
//             title: '错误提示：' + responseData.code,
//             message: responseData.message
//           }, 'error')
//         }
//       }
//     }
//   }
// })
axios.defaults.timeout = 50000
// http request 拦截器，通过这个，我们就可以把Cookie传到后台
axios.interceptors.request.use(
  config => {
    debugger
    const token = getCookie('token') // 获取Cookie
    config.data = JSON.stringify(config.data)
    config.headers = {
      'Content-Type': 'application/json' // 设置跨域头部
    }
    if (token) {
      config.token = token // 后台接收的参数
    }
    debugger;
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response
    }
    if (response.data.code === '200' || response.data.code === 200) {
      return response
    } else {
      if (response.data.code !== '200' || response.data.code !== 200) {
        const errorResponse = {}
        errorResponse.code = response.data.code
        errorResponse.message = response.data.message
        return Promise.reject(errorResponse)
      }
    }
  },
  error => {
    if (typeof error.response === 'undefined') {
      const errorResponse = {}
      errorResponse.code = 'DDS0000001'
      errorResponse.message = '系统错误！'
      return Promise.reject(errorResponse)
    } else {
      const errorResponse = {}
      errorResponse.code = error.response.status + ':' + error.response.statusText
      errorResponse.message = error.response.data
      return Promise.reject(errorResponse)
    }
  })

export default axios

/**
 * fetch 请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        const code = err.code
        NotificationInfo.install({
          title: '错误提示：' + code.split(':')[0],
          message: code.split(':')[1] + ': 连接服务器失败！'
        }, 'error')
      })
  })
}

export function exportpost(url, data = {}, responseType) {
  return axios({
    method: 'post',
    url: `${url}`,
    data: data,
    responseType: responseType
  })
}

export const uploadFileRequest = (url, body, params) => {
  return axios({
    method: 'post',
    url: `${url}`,
    data: body,
    params: params,
    responseType: 'blob'
  })
}
/**
 * patch 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

/**
 * put 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}
